<SCRIPT>function setFocus() {		if ((navigator.appName != "Netscape") && (parseFloat(navigator.appVersion) == 2)) {	return;	} else {	self.focus();	}}</SCRIPT><HTML><HEAD>	<TITLE>Decorator</TITLE></HEAD>

<BODY	BGCOLOR	= #FFFFFF
	TEXT = #000000onLoad="setFocus()";
>

<A NAME="top"></A>
<A NAME="Decorator"></A>
<A NAME="intent"></A>
<H2><A HREF="#alsoknownas"><IMG SRC="gifsb/down3.gif" BORDER=0 ALT="next: 
Also Known As"></A> Intent</H2> 

<A NAME="auto1000"></A>
<P>Attach additional responsibilities to an object dynamically.
Decorators provide a flexible alternative to subclassing for extending
functionality.</P>

<A NAME="alsoknownas"><A>
<H2><A HREF="#motivation"><IMG SRC="gifsb/down3.gif" BORDER=0 ALT="next: 
Motivation"></A> Also Known As</H2> 

<A NAME="auto1001"></A>
<P>Wrapper</P>

<A NAME="motivation"></A>
<H2><A HREF="#applicability"><IMG SRC="gifsb/down3.gif" BORDER=0 
ALT="next: Applicability"></A> Motivation</H2> 

<A NAME="auto1002"></A>
<P>Sometimes we want to add responsibilities to individual objects, not
to an entire class.  A graphical user interface toolkit, for example,
should let you add properties like borders or behaviors like scrolling
to any user interface component.</P>

<A NAME="auto1003"></A>
<P>One way to add responsibilities is with inheritance.  Inheriting a
border from another class puts a border around every subclass
instance.  This is inflexible, however, because the choice of border
is made statically. A client can't control how and when to decorate
the component with a border.</P>

<A NAME="dec-175"></A>
<P>A more flexible approach is to enclose the component in another object
that adds the border.  The enclosing object is called a
<STRONG>decorator</STRONG>.  The decorator conforms to the interface of the
component it decorates so that its presence is transparent to the
component's clients.  The decorator forwards requests to the component
and may perform additional actions (such as drawing a border) before
or after forwarding.  Transparency lets you nest decorators
recursively, thereby allowing an unlimited number of added
responsibilities.</P>

<P ALIGN=CENTER><IMG SRC="Pictures/decor066.gif"></P>

<A NAME="auto1004"></A>
<P>For example, suppose we have a TextView object that displays text in a
window.  TextView has no scroll bars by default, because we might not
always need them.  When we do, we can use a ScrollDecorator to add
them.  Suppose we also want to add a thick black border around the
TextView.  We can use a BorderDecorator to add this as well.  We
simply compose the decorators with the TextView to produce the desired
result.</P>

<A NAME="auto1005"></A>
<P>The following object diagram shows how to compose a TextView object
with BorderDecorator and ScrollDecorator objects to produce a
bordered, scrollable text view:</P>

<A NAME="scrolldecorator-176o"></A>
<A NAME="textview-176o"></A>
<P ALIGN=CENTER><IMG SRC="Pictures/decor065.gif"></P>

<A NAME="auto1006"></A>
<P>The ScrollDecorator and BorderDecorator classes are subclasses of
Decorator, an abstract class for visual components that decorate other
visual components.</P>

<A NAME="dec-176"></A>
<A NAME="scrolldecorator-176c"></A>
<A NAME="textview-176c"></A>
<P ALIGN=CENTER><IMG SRC="Pictures/decor067.gif"></P>

<A NAME="visual-comp"></A>
<P>VisualComponent is the abstract class for visual objects. It
defines their drawing and event handling interface.  Note how the
Decorator class simply forwards draw requests to its component,
and how Decorator subclasses can extend this operation.</P>

<A NAME="auto1007"></A>
<P>Decorator subclasses are free to add operations for specific
functionality.  For example, ScrollDecorator's ScrollTo operation lets
other objects scroll the interface <EM>if</EM> they know there happens to
be a ScrollDecorator object in the interface.  The important aspect of
this pattern is that it lets decorators appear anywhere a
VisualComponent can.  That way clients generally can't tell the
difference between a decorated component and an undecorated one, and
so they don't depend at all on the decoration.</P>

<A NAME="applicability"></A>
<H2><A HREF="#structure"><IMG SRC="gifsb/down3.gif" BORDER=0 ALT="next: 
Structure"></A> Applicability</H2> 

<A NAME="auto1008"></A>
<P>Use Decorator</P>

<UL>

<A NAME="auto1009"></A>
<LI>to add responsibilities to individual objects
dynamically and transparently, that is, without affecting other
objects.</LI>
<A NAME="auto1010"></A>
<P></P>
<A NAME="auto1011"></A>
<LI>for responsibilities that can be withdrawn.</LI>
<A NAME="auto1012"></A>
<P></P>
<A NAME="auto1013"></A>
<LI>when extension by subclassing is impractical.  Sometimes a large
number of independent extensions are possible and would produce an
explosion of subclasses to support every combination.  Or a class
definition may be hidden or otherwise unavailable for subclassing.</LI>

</UL>

<A NAME="structure"></A>
<H2><A HREF="#participants"><IMG SRC="gifsb/down3.gif" BORDER=0 ALT="next: 
Participants"></A> Structure</H2> 

<P ALIGN=CENTER><IMG SRC="Pictures/decor064.gif"></P>

<A NAME="participants"></A>

<A NAME="participants"></A>
<H2><A HREF="#collaborations"><IMG SRC="gifsb/down3.gif" BORDER=0 
ALT="next: Collaborations"></A> Participants</H2>

<UL>

<A NAME="auto1014"></A>
<LI><B>Component</B> (VisualComponent)</LI>

<A NAME="auto1015"></A>
<P></P>

    <UL>

    <A NAME="auto1016"></A>
<LI>defines the interface for objects that can have
    responsibilities added to them dynamically.</LI>

    </UL>

<A NAME="auto1017"></A>
<P></P>

<A NAME="auto1018"></A>
<LI><B>ConcreteComponent</B> (TextView)</LI>

<A NAME="auto1019"></A>
<P></P>

    <UL>

    <A NAME="auto1020"></A>
<LI>defines an object to which additional responsibilities
    can be attached.</LI>

    </UL>

<A NAME="auto1021"></A>
<P></P>

<A NAME="dec-part"></A>
<LI><B>Decorator</B></LI>

<A NAME="auto1022"></A>
<P></P>

    <UL>

    <A NAME="auto1023"></A>
<LI>maintains a reference to a Component object and defines an interface
    that conforms to Component's interface.</LI>

    </UL>

<A NAME="auto1024"></A>
<P></P>

<A NAME="auto1025"></A>
<LI><B>ConcreteDecorator</B> (BorderDecorator, ScrollDecorator)</LI>

<A NAME="auto1026"></A>
<P></P>

    <UL>

    <A NAME="auto1027"></A>
<LI>adds responsibilities to the component.</LI>

    </UL>

</UL>

<A NAME="collaborations"></A>
<H2><A HREF="#consequences"><IMG SRC="gifsb/down3.gif" BORDER=0 
ALT="next: Consequences"></A> Collaborations</H2>

<UL>

<A NAME="auto1028"></A>
<LI>Decorator forwards requests to its Component object.  It may optionally
perform additional operations before and after forwarding the request.</LI>

</UL>

<A NAME="consequences"></A>
<H2><A HREF="#implementation"><IMG SRC="gifsb/down3.gif" BORDER=0 
ALT="next: Implementation"></A> Consequences</H2> 

<A NAME="auto1029"></A>
<P>The Decorator pattern has at least two key benefits and two
liabilities:</P>

<OL>

<A NAME="auto1030"></A>
<LI><EM>More flexibility than static inheritance.</EM>
The Decorator pattern provides a more flexible way to add
responsibilities to objects than can be had with static (multiple)
inheritance.  With decorators, responsibilities can be added and
removed at run-time simply by attaching and detaching them. In
contrast, inheritance requires creating a new class for each
additional responsibility (e.g., BorderedScrollableTextView,
BorderedTextView).  This gives rise to many classes and increases the
complexity of a system.  Furthermore, providing different Decorator
classes for a specific Component class lets you mix and match
responsibilities.

<A NAME="auto1031"></A>
<P>Decorators also make it easy to add a property twice. For example, to
give a TextView a double border, simply attach two
BorderDecorators.  Inheriting from a Border class twice is error-prone
at best.</P>

</LI>
<A NAME="auto1032"></A>
<P></P>
<A NAME="auto1033"></A>
<LI><EM>Avoids feature-laden classes high up in the hierarchy.</EM>
Decorator offers a pay-as-you-go approach to adding responsibilities.
Instead of trying to support all foreseeable features in a complex,
customizable class, you can define a simple class and add functionality
incrementally with Decorator objects.  Functionality can be composed from
simple pieces.  As a result, an application needn't pay for features
it doesn't use.  It's also easy to define new kinds of Decorators
independently from the classes of objects they extend, even for
unforeseen extensions.  Extending a complex class tends to expose
details unrelated to the responsibilities you're adding.</LI>
<A NAME="auto1034"></A>
<P></P>
<A NAME="auto1035"></A>
<LI><EM>A decorator and its component aren't identical.</EM>
A decorator acts as a transparent enclosure.  But from an object
identity point of view, a decorated component is not identical to the
component itself.  Hence you shouldn't rely on object identity when
you use decorators.</LI>
<A NAME="auto1036"></A>
<P></P>
<A NAME="auto1037"></A>
<LI><EM>Lots of little objects.</EM>
A design that uses Decorator often results in systems composed of
lots of little objects that all look alike.  The objects differ only
in the way they are interconnected, not in their class or in the value
of their variables.  Although these systems are easy to customize
by those who understand them, they can be hard to learn and debug.</LI>

</OL>

<A NAME="implementation"></A>
<H2><A HREF="#samplecode"><IMG SRC="gifsb/down3.gif" BORDER=0 ALT="next: 
Sample Code"></A> Implementation</H2> 

<A NAME="auto1038"></A>
<P>Several issues should be considered when applying the Decorator pattern:</P>

<OL>

<A NAME="auto1039"></A>
<LI><EM>Interface conformance.</EM>
A decorator object's interface must conform to the interface of the
component it decorates.  ConcreteDecorator classes must therefore
inherit from a common class (at least in C++).</LI>

<A NAME="auto1040"></A>
<P></P>

<A NAME="auto1041"></A>
<LI><EM>Omitting the abstract Decorator class.</EM>
There's no need to define an abstract Decorator class when you only
need to add one responsibility.  That's often the case when you're
dealing with an existing class hierarchy rather than designing a new
one.  In that case, you can merge Decorator's responsibility for
forwarding requests to the component into the ConcreteDecorator.</LI>

<A NAME="auto1042"></A>
<P></P>

<A NAME="lightvsheavy"></A>
<LI><EM>Keeping Component classes lightweight.</EM>
To ensure a conforming interface, components and decorators must
descend from a common Component class. It's important to keep this
common class lightweight; that is, it should focus on defining an
interface, not on storing data.  The definition of the data
representation should be deferred to subclasses; otherwise the
complexity of the Component class might make the decorators too
heavyweight to use in quantity.  Putting a lot of functionality into
Component also increases the probability that concrete subclasses will
pay for features they don't need.</LI>

<A NAME="auto1043"></A>
<P></P>

<A NAME="dec-strat"></A>
<A NAME="strat-vs-decor"></A>
<LI><EM>Changing the skin of an object versus changing its guts.</EM>
We can think of a decorator as a skin over an object that changes its
behavior. An alternative is to change the object's guts.  
The <A HREF="pat5ifs.htm" TARGET="_mainDisplayFrame">Strategy (315)</A> pattern is a good example of a pattern for
changing the guts.

<A NAME="auto1044"></A>
<P>Strategies are a better choice in situations where the Component class
is intrinsically heavyweight, thereby making the Decorator pattern too
costly to apply.  In the Strategy pattern, the component forwards some
of its behavior to a separate strategy object.  The Strategy pattern
lets us alter or extend the component's functionality by replacing the
strategy object.</P>

<A NAME="auto1045"></A>
<P>For example, we can support different border styles by having the
component defer border-drawing to a separate Border object.  The
Border object is a Strategy object that encapsulates a border-drawing
strategy. By extending the number of strategies from just one to an
open-ended list, we achieve the same effect as nesting decorators
recursively.</P>

<A NAME="adorner"></A>
<A NAME="bedrock1"></A>
<A NAME="macapp-dec"></A>
<P>In MacApp 3.0 [<A HREF="bibfs.htm#macapp" TARGET="_mainDisplayFrame">App89</A>] and Bedrock [<A HREF="bibfs.htm#bedrock" TARGE
T="_mainDisplayFrame">Sym93a</A>], for example,
graphical components (called "views") maintain a list of "adorner"
objects that can attach additional adornments like borders to a view
component.  If a view has any adorners attached, then it gives them a
chance to draw additional embellishments.  MacApp and Bedrock must
use this approach because the View class is heavyweight.  It would be
too expensive to use a full-fledged View just to add a border.</P>

<A NAME="auto1046"></A>
<P>Since the Decorator pattern only changes a component from the outside,
the component doesn't have to know anything about its decorators; that
is, the decorators are transparent to the component:</P>

<A NAME="dec-180o"></A>
<P ALIGN=CENTER><IMG SRC="Pictures/deco-069.gif"></P>

<A NAME="auto1047"></A>
<P>With strategies, the component itself knows about possible extensions.
So it has to reference and maintain the corresponding strategies:</P>

<A NAME="strat-180o"></A>
<P ALIGN=CENTER><IMG SRC="Pictures/deco-068.gif"></P>

<A NAME="dec-180"></A>
<P>The Strategy-based approach might require modifying the component to
accommodate new extensions.  On the other hand, a strategy can have
its own specialized interface, whereas a decorator's interface must
conform to the component's. A strategy for rendering a border, for
example, need only define the interface for rendering a border
(DrawBorder, GetWidth, etc.), which means that the strategy can be
lightweight even if the Component class is heavyweight.</P>

<A NAME="bedrock2"></A>
<A NAME="macapp-dec2"></A>
<P>MacApp and Bedrock use this approach for more than just adorning
views. They also use it to augment the event-handling behavior of
objects.  In both systems, a view maintains a list of "behavior"
objects that can modify and intercept events. The view gives each of
the registered behavior objects a chance to handle the event before
nonregistered behaviors, effectively overriding them.  You can
decorate a view with special keyboard-handling support, for example,
by registering a behavior object that intercepts and handles key
events.</P>

</OL>

<A NAME="samplecode"></A>
<H2><A HREF="#knownuses"><IMG SRC="gifsb/down3.gif" BORDER=0 ALT="next: 
Known Uses"></A> Sample Code</H2> 

<A NAME="auto1048"></A>
<P>The following code shows how to implement user interface decorators in
C++.  We'll assume there's a Component class called
<CODE>VisualComponent</CODE>.</P>

<A NAME="auto1049"></A>
<PRE>
    class VisualComponent {
    public:
        VisualComponent();
    
        virtual void Draw();
        virtual void Resize();
        // ...
    };
</PRE>

<A NAME="auto1050"></A>
<P>We define a subclass of <CODE>VisualComponent</CODE> called
<CODE>Decorator</CODE>, which we'll subclass to obtain different
decorations.</P>

<A NAME="auto1051"></A>
<PRE>
    class Decorator : public VisualComponent {
    public:
        Decorator(VisualComponent*);
    
        virtual void Draw();
        virtual void Resize();
        // ...
    private:
        VisualComponent* _component;
    };
</PRE>


<A NAME="auto1052"></A>
<P><CODE>Decorator</CODE> decorates the <CODE>VisualComponent</CODE>
referenced by the <CODE>_component</CODE> instance variable, which is
initialized in the constructor.  For each operation in
<CODE>VisualComponent</CODE>'s interface, <CODE>Decorator</CODE> defines a
default implementation that passes the request on to
<CODE>_component</CODE>:</P>

<A NAME="auto1053"></A>
<PRE>
    void Decorator::Draw () {
        _component->Draw();
    }
    
    void Decorator::Resize () {
        _component->Resize();
    }
</PRE>

<A NAME="auto1054"></A>
<P>Subclasses of <CODE>Decorator</CODE> define specific decorations.  For
example, the class <CODE>BorderDecorator</CODE> adds a border to its
enclosing component.  <CODE>BorderDecorator</CODE> is a subclass of
<CODE>Decorator</CODE> that overrides the <CODE>Draw</CODE> operation
to draw the border.  <CODE>BorderDecorator</CODE> also defines a private
<CODE>DrawBorder</CODE> helper operation that does the drawing.  The
subclass inherits all other operation implementations from
<CODE>Decorator</CODE>.</P>

<A NAME="auto1055"></A>
<PRE>
    class BorderDecorator : public Decorator {
    public:
        BorderDecorator(VisualComponent*, int borderWidth);
    
        virtual void Draw();
    private:
        void DrawBorder(int);
    private:
        int _width;
    };
    
    void BorderDecorator::Draw () {
        Decorator::Draw();
        DrawBorder(_width);
    }
</PRE>

<A NAME="auto1056"></A>
<P>A similar implementation would follow for <CODE>ScrollDecorator</CODE> and
<CODE>DropShadowDecorator</CODE>, which would add scrolling and drop shadow
capabilities to a visual component.</P>

<A NAME="auto1057"></A>
<P>Now we can compose instances of these classes to provide different
decorations.  The following code illustrates how we can use
decorators to create a bordered scrollable <CODE>TextView</CODE>.</P>

<A NAME="auto1058"></A>
<P>First, we need a way to put a visual component into a window object.
We'll assume our <CODE>Window</CODE> class provides a
<CODE>SetContents</CODE> operation for this purpose:</P>

<A NAME="auto1059"></A>
<PRE>
    void Window::SetContents (VisualComponent* contents) {
        // ...
    }
</PRE>

<A NAME="auto1060"></A>
<P>Now we can create the text view and a window to put it in:</P>

<A NAME="auto1061"></A>
<PRE>
    Window* window = new Window;
    TextView* textView = new TextView;
</PRE>


<A NAME="auto1062"></A>
<P><CODE>TextView</CODE> is a <CODE>VisualComponent</CODE>, which lets us put it
into the window:</P>

<A NAME="auto1063"></A>
<PRE>
    window->SetContents(textView);
</PRE>

<A NAME="auto1064"></A>
<P>But we want a bordered and scrollable <CODE>TextView</CODE>.  So we
decorate it accordingly before putting it in the window.</P>

<A NAME="auto1065"></A>
<PRE>
    window->SetContents(
        new BorderDecorator(
            new ScrollDecorator(textView), 1
        )
    );
</PRE>

<A NAME="auto1066"></A>
<P>Because <CODE>Window</CODE> accesses its contents through the
<CODE>VisualComponent</CODE> interface, it's unaware of the decorator's
presence.  You, as the client, can still keep track of the text view if you
have to interact with it directly, for example, when you need to
invoke operations that aren't part of the <CODE>VisualComponent</CODE>
interface.  Clients that rely on the component's identity should refer
to it directly as well.</P>

<A NAME="knownuses"></A>
<H2><A HREF="#relatedpatterns"><IMG SRC="gifsb/down3.gif" BORDER=0 
ALT="next: Related Patterns"></A> Known Uses</H2> 

<A NAME="debuggingglyph"></A>
<P>Many object-oriented user interface toolkits use decorators to add
graphical embellishments to widgets.  Examples include
InterViews [<A HREF="bibfs.htm#interviews_composition" TARGET="_mainDisplayFrame">LVC98</A>, <A HREF="bibfs.htm#InterViews3.1" TARGET=
"_mainDisplayFrame">LCI+92</A>],
ET++ [<A HREF="bibfs.htm#et++" TARGET="_mainDisplayFrame">WGM88</A>], and the
ObjectWorks\Smalltalk class library [<A HREF="bibfs.htm#parcplace_smalltalk" TARGET="_mainDisplayFrame">Par90</A>].  More
exotic applications of Decorator are the DebuggingGlyph from
InterViews and the PassivityWrapper from ParcPlace Smalltalk. A
DebuggingGlyph prints out debugging information before and after it
forwards a layout request to its component.  This trace information
can be used to analyze and debug the layout behavior of objects in a
complex composition.  The PassivityWrapper can enable or disable user
interactions with the component.</P>

<A NAME="et-use-decor"></A>
<P>But the Decorator pattern is by no means limited to graphical user
interfaces, as the following example (based on the
ET++ streaming classes [<A HREF="bibfs.htm#et++" TARGET="_mainDisplayFrame">WGM88</A>]) illustrates.</P>

<A NAME="filestr-183"></A>
<A NAME="stream"></A>
<P>Streams are a fundamental abstraction in most I/O facilities.  A
stream can provide an interface for converting objects into a sequence
of bytes or characters.  That lets us transcribe an object to a file
or to a string in memory for retrieval later. A straightforward way to
do this is to define an abstract Stream class with subclasses
MemoryStream and FileStream.  But suppose we also want to be able to
do the following:</P>

<UL>

<A NAME="lempelziv"></A>
<LI>Compress the stream data using different compression
algorithms (run-length encoding, Lempel-Ziv, etc.).</LI>

<A NAME="ascii7stream"></A>
<LI>Reduce the stream data to 7-bit ASCII characters so that it can be
transmitted over an ASCII communication channel.</LI>

</UL>

<A NAME="auto1067"></A>
<P>The Decorator pattern gives us an elegant way to add these responsibilities
to streams.  The diagram below shows one solution to the problem:</P>

<A NAME="183c"></A>
<P ALIGN=CENTER><IMG SRC="Pictures/strea010.gif"></P>

<A NAME="auto1068"></A>
<P>The Stream abstract class maintains an internal buffer and provides
operations for storing data onto the stream (PutInt, PutString).
Whenever the buffer is full, Stream calls the abstract operation
HandleBufferFull, which does the actual data transfer.  The FileStream
version of this operation overrides this operation to transfer the
buffer to a file.</P>

<A NAME="streamdecorator"></A>
<P>The key class here is StreamDecorator, which maintains a reference to
a component stream and forwards requests to it. StreamDecorator
subclasses override HandleBufferFull and perform additional actions
before calling StreamDecorator's HandleBufferFull operation.</P>

<A NAME="auto1069"></A>
<P>For example, the CompressingStream subclass compresses the data, and
the ASCII7Stream converts the data into 7-bit ASCII.  Now, to create a
FileStream that compresses its data <EM>and</EM> converts the compressed
binary data to 7-bit ASCII, we decorate a FileStream with a
CompressingStream and an ASCII7Stream:</P>

<A NAME="auto1070"></A>
<PRE>
    Stream* aStream = new CompressingStream(
        new ASCII7Stream(
             new FileStream("aFileName")
        )
    );
    aStream->PutInt(12);
    aStream->PutString("aString");
</PRE>

<A NAME="relatedpatterns"></A>
<H2><A HREF="#last"><IMG SRC="gifsb/down3.gif" BORDER=0 ALT="next: 
navigation"></A> Related Patterns</H2> 

<A NAME="compadapt"></A>
<P><A HREF="pat4afs.htm" TARGET="_mainDisplayFrame">Adapter (139)</A>: A
decorator is different from an adapter in that a decorator only
changes an object's responsibilities, not its interface; an adapter
will give an object a completely new interface.</P>

<A NAME="auto1071"></A>
<P><A HREF="pat4cfs.htm" TARGET="_mainDisplayFrame">Composite (163)</A>:
A decorator can be viewed as a degenerate composite with only one
component.  However, a decorator adds additional responsibilities&#151;it
isn't intended for object aggregation.</P>

<A NAME="auto1072"></A>
<P><A HREF="pat5ifs.htm" TARGET="_mainDisplayFrame">Strategy (315)</A>: A
decorator lets you change the skin of an object; a strategy lets
you change the guts.  These are two alternative ways of changing
an object.</P>

<A NAME="last"></A>
<P><A HREF="#intent"><IMG SRC="gifsb/up3.gif" BORDER=0></A><BR>
<A HREF="pat4efs.htm" TARGET="_mainDisplayFrame"><IMG SRC="gifsb/rightar3.gif"
	ALIGN=TOP BORDER=0></A> <A HREF="pat4efs.htm"
	TARGET="_mainDisplayFrame">Facade</A><BR>
<A HREF="pat4cfs.htm" TARGET="_mainDisplayFrame"><IMG SRC="gifsb/leftarr3.gif"
	ALIGN=TOP BORDER=0></A> <A HREF="pat4cfs.htm"
	TARGET="_mainDisplayFrame">Composite</A>
</P>

</BODY>

</HTML>

<A NAME="auto1073"></A>
<P>

<A NAME="auto1074"></A>
<P>
